package com.hxl.alert.scheduler;

import com.hxl.alert.client.XxlJobApiClient;
import com.hxl.alert.constant.CacheConstants;
import com.hxl.alert.entity.AlertOriginBase;
import com.hxl.alert.utils.AlertTimeUtils;
import com.hxl.alert.utils.RedisUtils;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import javafx.scene.control.Alert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class AlarmTimeoutHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private XxlJobApiClient xxlJobClient;

    @XxlJob("alarmTimeoutHandler")
    public void execute() {
        String taskId = XxlJobHelper.getJobParam();
        String redisKey = CacheConstants.YUEXIAN_KEY + taskId;

        Long pollCount = pollCount(taskId);
        logger.info("越限告警任务-taskId{} 调度执行第{}次", taskId, pollCount);
        //越限告警任务提前结束
        if (pollCount >= 60 & redisUtils.getExpire(redisKey, TimeUnit.MILLISECONDS) <= 0) {
            //TODO 越限告警1分钟内无设备故障告警时触发独立计算
            AlertOriginBase yueXianAlert = (AlertOriginBase) redisUtils.get(CacheConstants.RECEIVE_KEY + taskId.split("_")[1]);
            processIndependentCalculation(yueXianAlert);

            // 清理Redis数据
            redisUtils.delete(redisKey);
            xxlJobClient.findJobIdsAndStopJobByParam(taskId); // 根据参数终止任务
            logger.info("####独立计算完成，清理数据");
            XxlJobHelper.log("独立计算完成，清理数据");
        }
    }

    private void processIndependentCalculation(AlertOriginBase alert) {
        // 实现独立计算逻辑（例如：仅处理越限告警）
        logger.info("执行独立计算，设备ID={}，告警ID={}", alert.getDevId(), alert.getFaultId());
    }

    public Long pollCount(String taskId) {
        // 检查是否超时（示例：通过Redis记录轮询次数）
        return redisUtils.incrBy("alert:poll_count:" + taskId, 1);
    }
}